//
//  LSUserAccount.swift
//  MicroBlog
//
//  Created by lj on 15/9/6.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

/// 用户账户
class LSUserAccount: NSObject, NSCoding {
    
    ///用于调用access_token，接口获取授权后的access token
    var access_token:String?
    /// access_token的生命周期，单位是秒数。
    var expires_in: NSTimeInterval = 0{
        didSet{
        //计算过期日期
        expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    ///过期日期
    var expiresDate: NSDate?
    /// 当前授权用户的UID。
    var uid:String?
    
    /// 友好显示名称
    var name:String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large:String?
    
    
    init(dict:[String:AnyObject]){
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
           
    }
    
    /// 对象的描述信息
    override var description: String{
        let keys = ["access_token","expires_in","expiresDate","uid","name","avatar_large"]
        
        //KVC的模型字典
        return dictionaryWithValuesForKeys(keys).description
    }
    
    /// 归档解档的保存路径
    static let accountPath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
    /// 归档保存当前对象
    func saveUserAccount(){
        printLog("保存路径：\(LSUserAccount.accountPath)")
        
        //键值归档
        NSKeyedArchiver.archiveRootObject(self, toFile: LSUserAccount.accountPath)
    }

    /// 加载用户账户
    ///
    /// - returns: 账号信息，如果还没有登陆返回nil
    class func loadUserAccount()->LSUserAccount? {
        
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? LSUserAccount
        
        //判断token的有效期
        if let date = account?.expiresDate {
            // 比较日期 date > NSDate() 结果是降序
            if date.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }
        }
        
        return nil
    }
    
    // MARK: -NSCoding
    /// 归档:将当前对象保存到磁盘以前转换成二进制数据
    func encodeWithCoder(acoder:NSCoder){
        acoder.encodeObject(access_token, forKey: "access_token")
        acoder.encodeObject(expiresDate, forKey: "expiresDate")
        acoder.encodeObject(uid, forKey: "uid")
        acoder.encodeObject(name, forKey: "name")
        acoder.encodeObject(avatar_large, forKey: "avatar_large")

    }
    
    /// 解档:将二进制数据从磁盘中加载，转换成自定义对象时调用
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
    }
    
}
